
package com.hlkj.pay.app.merchant.ext.impl.hnapay.handler;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.pay.app.merchant.ext.dto.access.ChannelMerchantAccessAuthQueryContext;
import com.hlkj.pay.app.merchant.ext.dto.access.ChannelMerchantBusinessContext;
import com.hlkj.pay.app.merchant.ext.impl.hnapay.constant.HnapayConstant;
import com.hlkj.pay.app.merchant.ext.impl.hnapay.dto.HnapayConfig;
import com.hlkj.pay.app.merchant.ext.impl.hnapay.utils.HttpUtils;
import com.hlkj.pay.dto.merchant.MerchantWechatConfigAppIdDto;
import com.hlkj.pay.dto.merchant.MerchantWechatConfigListDto;
import com.hlkj.pay.dto.pay.PayCommonAppDto;
import com.hlkj.pay.enums.MerchantEnum;
import com.hlkj.pay.enums.PayEnums;
import com.hlkj.pay.infrastructure.model.merchant.MerchantAccessAuthDO;
import com.hlkj.pay.infrastructure.model.merchant.MerchantAccessInfoDO;
import com.hlkj.pay.vo.order.req.MerchantChannelSplitReq;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.utils.StringPool;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author HlpayTeam
 * @date 2024/10/16 9:10
 */
@Slf4j
@Repository
@RequiredArgsConstructor
@Component
public class HnapayMerchantAccessConfigHandler {

    @Value("${hlkj.domain}")
    private String domainHost;

    private final HnapayMerchantCommonParamsHandle paramsHandle;

    /**
     * 微信/支付宝 报备
     * 
     * @param channelMerchantBusinessContext
     */
    public void processSubApply(ChannelMerchantBusinessContext channelMerchantBusinessContext) {
        CommonResult<HnapayConfig> payConfigCommonResult = paramsHandle.channelConfig(channelMerchantBusinessContext.getProviderChannelConfig());
        // 配置转换
        if (!payConfigCommonResult.isSuccess()) {
            channelMerchantBusinessContext.setRemark(payConfigCommonResult.getMsg());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
            return;
        }
        try {
            HnapayConfig payConfig = payConfigCommonResult.getData();
            List<MerchantAccessAuthDO> list = new ArrayList<>();
            MerchantAccessAuthDO aliAuth = alipayApply(channelMerchantBusinessContext, payConfig);
            if (aliAuth != null) list.add(aliAuth);
            log.error("新生支付宝报备结果1: {}## {}", list.size(), JSONUtil.toJsonStr(list));
            MerchantAccessAuthDO wxAuth = wechatApply(channelMerchantBusinessContext, payConfig);
            if (wxAuth != null) list.add(wxAuth);
            log.error("新生支付宝报备结果2: {}## {}", list.size(), JSONUtil.toJsonStr(list));
            channelMerchantBusinessContext.setMerchantAccessAuthList(list);
            channelMerchantBusinessContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.APPROVE_SUCCESS);
        } catch (Exception e) {
            log.error("新生微信/支付宝报备请求异常,失败信息 message: {}", e.getMessage(), e);
            channelMerchantBusinessContext.setRemark("新生微信/支付宝报备请求异常,异常信息" + e.getMessage());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
        }

    }

    //报备查询
    public void processSubApplyQuery(ChannelMerchantBusinessContext channelMerchantBusinessContext) {
        CommonResult<HnapayConfig> payConfigCommonResult = paramsHandle.channelConfig(channelMerchantBusinessContext.getProviderChannelConfig());
        // 配置转换
        if (!payConfigCommonResult.isSuccess()) {
            channelMerchantBusinessContext.setRemark(payConfigCommonResult.getMsg());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
            return;
        }
        try {
            HnapayConfig payConfig = payConfigCommonResult.getData();
            List<MerchantAccessAuthDO> merchantAccessAuthList = channelMerchantBusinessContext.getMerchantAccessDto().getMerchantAccessAuthList();
            for (int i = 0; i < merchantAccessAuthList.size(); i++) {
                MerchantAccessAuthDO merchantAccessAuthDO = merchantAccessAuthList.get(i);
                CommonResult<Map<String, String>> authCommonResult = HnapayMerchantParamsHandle.queryApplyStatus(merchantAccessAuthDO.getSerialCode(), payConfig);
                Map<String, String> authParams = authCommonResult.getData();
                String authUrl = HnapayConstant.DOMAIN_PROD + HnapayConstant.MERCHANT_QUERY;
                log.info("新生子商户报备状态查询请求参数:{}", JsonUtils.toJsonString(authParams));
                String authResponse = HttpUtils.postForm(authUrl, authParams);
                log.info("新生子商户报备状态查询返回参数:{}", authResponse);
                JSONObject authResp = JsonUtils.parseObj(authResponse);
                if (!"0000".equals(authResp.getStr("resultCode"))) {
                    channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
                    channelMerchantBusinessContext.setRemark(authResp.getStr("errorMsg") + "  " + authResp.getStr("remark"));
                    merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.REJECT.getCode());
                    log.error("新生子商户报备状态查询异常 message: {}", authResp.getStr("errorMsg"));
                } else {
                    merchantAccessAuthDO.setSubMchId(authResp.getStr("subReportedNo"));
                    switch (authResp.getStr("reportedStatus")) {
                        case "00":
                            merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.APPROVE.getCode());
                            break;
                        case "02":
                            merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.APPROVEING.getCode());
                            break;
                        case "03":
                            merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.FROZEN.getCode());
                            break;
                        case "01":
                        case "04":
                        case "05":
                            merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.REJECT.getCode());
                            merchantAccessAuthDO.setRejectReason(authResp.getStr("remark"));
                            break;
                    }
                }
            }
            channelMerchantBusinessContext.setMerchantAccessAuthList(merchantAccessAuthList);
        } catch (Exception e) {
            log.error("新生子商户报备状态查询请求异常 message: {}", e.getMessage(), e);
            channelMerchantBusinessContext.setRemark("新生子商户报备状态查询请求异常 " + e.getMessage());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
        }
    }

    //支付宝报备
    private MerchantAccessAuthDO alipayApply(ChannelMerchantBusinessContext channelMerchantBusinessContext, HnapayConfig payConfig) throws Exception {
        CommonResult<Map<String, String>> paramsCommonResult  = HnapayMerchantParamsHandle.alipayApplyParams(channelMerchantBusinessContext, payConfig);
        Map<String, String> params = paramsCommonResult.getData();
        String url = HnapayConstant.DOMAIN_PROD + HnapayConstant.MERCHANT_ALIPAY_ADD;
        log.info("新生支付宝报备请求参数:{}", JsonUtils.toJsonString(params));
        String response = HttpUtils.postForm(url, params);
        log.info("新生支付宝报备返回参数:{}", response);
        MerchantAccessAuthDO merchantAccessAuthDO = new MerchantAccessAuthDO();
        MerchantAccessInfoDO merchantAccessInfo = channelMerchantBusinessContext.getMerchantAccessDto().getMerchantAccessInfo();
        merchantAccessAuthDO.setAccessId(merchantAccessInfo.getId());
        merchantAccessAuthDO.setType(PayEnums.PAY_TYPE.ALIPAY.getCode());
        merchantAccessAuthDO.setSn(merchantAccessInfo.getSn());
        merchantAccessAuthDO.setMchId(payConfig.getAliChannelCode());

        JSONObject respObj = JsonUtils.parseObj(response);
        if (!"0000".equals(respObj.getStr("resultCode"))) {
//            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
//            channelMerchantBusinessContext.setRemark("新生支付宝报备失败：" + respObj.getStr("errorMsg"));
            log.error("新生支付宝报备失败 message: {}", respObj.getStr("errorMsg"));
            merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.REJECT.getCode());
            merchantAccessAuthDO.setRejectReason(respObj.getStr("errorMsg"));
            return null;
        } else {
            merchantAccessAuthDO.setSerialCode(respObj.getStr("reportedNo"));
            merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.APPROVEING.getCode());
            return merchantAccessAuthDO;
//            channelMerchantBusinessContext.setProcessStatus(Boolean.TRUE);
//            channelMerchantBusinessContext.setRemark("报备成功");
        }
//        channelMerchantBusinessContext.getMerchantAccessAuthList().add(merchantAccessAuthDO);
    }

    //微信报备
    private MerchantAccessAuthDO wechatApply(ChannelMerchantBusinessContext channelMerchantBusinessContext, HnapayConfig payConfig) throws Exception {
        CommonResult<Map<String, String>> paramsCommonResult  = HnapayMerchantParamsHandle.wechatApplyParams(channelMerchantBusinessContext, payConfig);
        Map<String, String> params = paramsCommonResult.getData();
        String url = HnapayConstant.DOMAIN_PROD + HnapayConstant.MERCHANT_WX_ADD;
        log.info("新生微信报备请求参数:{}", JsonUtils.toJsonString(params));
        String response = HttpUtils.postForm(url, params);
        log.info("新生微信报备返回参数:{}", response);
        MerchantAccessAuthDO merchantAccessAuthDO = new MerchantAccessAuthDO();
        MerchantAccessInfoDO merchantAccessInfo = channelMerchantBusinessContext.getMerchantAccessDto().getMerchantAccessInfo();
        merchantAccessAuthDO.setAccessId(merchantAccessInfo.getId());
        merchantAccessAuthDO.setType(PayEnums.PAY_TYPE.WECHAT.getCode());
        merchantAccessAuthDO.setSn(merchantAccessInfo.getSn());
        merchantAccessAuthDO.setMchId(payConfig.getWxChannelCode());

        JSONObject respObj = JsonUtils.parseObj(response);
        if (!"0000".equals(respObj.getStr("resultCode"))) {
//            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
//            channelMerchantBusinessContext.setRemark("新生微信报备失败：" + respObj.getStr("errorMsg"));
            log.error("新生微信报备失败 message: {}", respObj.getStr("errorMsg"));
            merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.REJECT.getCode());
            merchantAccessAuthDO.setRejectReason(respObj.getStr("errorMsg"));
            return null;
        } else {
            merchantAccessAuthDO.setSerialCode(respObj.getStr("reportedNo"));
            merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.APPROVEING.getCode());
//            channelMerchantBusinessContext.getMerchantAccessAuthList().add(merchantAccessAuthDO);
            return  merchantAccessAuthDO;
//            channelMerchantBusinessContext.setProcessStatus(Boolean.TRUE);
//            channelMerchantBusinessContext.setRemark("报备成功");
        }
    }

    public void wechatConfigInit(ChannelMerchantBusinessContext channelMerchantBusinessContext) {
        CommonResult<HnapayConfig> payConfigCommonResult = paramsHandle.channelConfig(channelMerchantBusinessContext.getProviderChannelConfig());
        // 配置转换
        if (!payConfigCommonResult.isSuccess()) {
            channelMerchantBusinessContext.setRemark(payConfigCommonResult.getMsg());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
            return;
        }

        try {
            HnapayConfig payConfig = payConfigCommonResult.getData();

            List<PayCommonAppDto> payCommonAppList = channelMerchantBusinessContext.getPayCommonAppList();
            List<PayCommonAppDto> wechatCommonApp = null;
            if (!CollectionUtils.isEmpty(payCommonAppList)) {
                wechatCommonApp = payCommonAppList.stream().filter(payCommonAppDto -> PayEnums.PAY_TYPE.WECHAT.getCode().equals(payCommonAppDto.getPayWayDO().getType()))
                        .collect(Collectors.toList());
            }
            // 没有微信执行 配置完成
            if (CollectionUtils.isEmpty(wechatCommonApp)) {
                return;
            }
            List<MerchantAccessAuthDO> merchantAccessAuthList = channelMerchantBusinessContext.getMerchantAccessDto().getMerchantAccessAuthList().stream()
                    .filter(merchantAccessAuthDO -> PayEnums.PAY_TYPE.WECHAT.getCode().equals(merchantAccessAuthDO.getType())).collect(Collectors.toList());

            channelMerchantBusinessContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.ALIPAY_AUTH);

            for (MerchantAccessAuthDO merchantAccessAuthDO : merchantAccessAuthList) {
                if (!StringUtils.hasText(merchantAccessAuthDO.getSubMchId())) {
                    continue;
                }
                for (PayCommonAppDto payCommonAppDto : wechatCommonApp) {
                    CommonResult<Map<String, String>> authCommonResult = HnapayMerchantParamsHandle.wxConfigInit(payConfig, merchantAccessAuthDO, payCommonAppDto.getAppId(), "");
                    Map<String, String> authParams = authCommonResult.getData();
                    String authUrl = HnapayConstant.DOMAIN_PROD + HnapayConstant.WECHAT_APPID_CONFIG;
                    log.info("新生初始化微信参数配置APPID请求参数:{}", JsonUtils.toJsonString(authParams));
                    String authResponse = HttpUtils.postForm(authUrl, authParams);
                    log.info("新生初始化微信参数配置APPID返回参数:{}", authResponse);


                    String authPath = domainHost + StringPool.SLASH;;
                    authCommonResult = HnapayMerchantParamsHandle.wxConfigInit(payConfig, merchantAccessAuthDO, "", authPath);
                    authParams = authCommonResult.getData();
                    authUrl = HnapayConstant.DOMAIN_PROD + HnapayConstant.WECHAT_PATH_CONFIG;;
                    log.info("新生初始化微信参数配置授权目录请求参数:{}", JsonUtils.toJsonString(authParams));
                    authResponse = HttpUtils.postForm(authUrl, authParams);
                    log.info("新生初始化微信参数配置授权目录返回参数:{}", authResponse);

                }
            }
            channelMerchantBusinessContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.WECHAT_AUTH);
        } catch (Exception e) {
            log.error("新生初始化微信参数配置请求失败,失败信息 message: {}", e.getMessage(), e);
            channelMerchantBusinessContext.setRemark("新生初始化微信参数配置请求失败,失败信息" + e.getMessage());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
        }
    }

    /**
     * 微信 appid配置，
     *
     * @param channelMerchantBusinessContext
     */
    public void processWxAuth(ChannelMerchantBusinessContext channelMerchantBusinessContext) {
        CommonResult<HnapayConfig> payConfigCommonResult = paramsHandle.channelConfig(channelMerchantBusinessContext.getProviderChannelConfig());
        // 配置转换
        if (!payConfigCommonResult.isSuccess()) {
            channelMerchantBusinessContext.setRemark(payConfigCommonResult.getMsg());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
            return;
        }

        try {
            HnapayConfig payConfig = payConfigCommonResult.getData();
            MerchantAccessAuthDO merchantAccessAuth = channelMerchantBusinessContext.getMerchantAccessAuth();
            CommonResult<Map<String, String>> authCommonResult = HnapayMerchantParamsHandle.wxConfig(channelMerchantBusinessContext, payConfig, merchantAccessAuth);
            Map<String, String> authParams = authCommonResult.getData();
            String authUrl = HnapayConstant.DOMAIN_PROD + HnapayConstant.WECHAT_APPID_CONFIG;
            if (!authParams.containsKey("appId")) {
                authUrl = HnapayConstant.DOMAIN_PROD + HnapayConstant.WECHAT_PATH_CONFIG;
            }
            log.info("新生微信参数配置请求参数:{}", JsonUtils.toJsonString(authParams));
            String authResponse = HttpUtils.postForm(authUrl, authParams);
            log.info("新生微信参数配置返回参数:{}", authResponse);
            JSONObject authResp = JsonUtils.parseObj(authResponse);
            if (!"0000".equals(authResp.getStr("resultCode"))) {
                channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
                channelMerchantBusinessContext.setRemark(authResp.getStr("errorMsg"));
                log.error("新生微信参数配置异常 message: {}", authResp.getStr("errorMsg"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("新生微信参数配置请求失败,失败信息 message: {}", e.getMessage());
            channelMerchantBusinessContext.setRemark("新生微信参数配置请求失败,失败信息" + e.getMessage());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
        }
    }

    public void channelSplit(ChannelMerchantBusinessContext channelMerchantBusinessContext) {
        CommonResult<HnapayConfig> payConfigCommonResult = paramsHandle.channelConfig(channelMerchantBusinessContext.getProviderChannelConfig());
        // 配置转换
        if (!payConfigCommonResult.isSuccess()) {
            channelMerchantBusinessContext.setRemark(payConfigCommonResult.getMsg());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
            return;
        }

        try {
            HnapayConfig payConfig = payConfigCommonResult.getData();
            MerchantChannelSplitReq splitReq = channelMerchantBusinessContext.getMerchantChannelSplitReq();
            String response = "";
            MerchantAccessAuthDO merchantAccessAuthDO = new MerchantAccessAuthDO();
            if ("WECHAT".equals(splitReq.getTradeType())) {
                merchantAccessAuthDO.setType(1);
                CommonResult<Map<String, String>> paramsCommonResult  = HnapayMerchantParamsHandle.wechatApplyParams(channelMerchantBusinessContext, payConfig);
                Map<String, String> params = paramsCommonResult.getData();
                String url = HnapayConstant.DOMAIN_PROD + HnapayConstant.MERCHANT_WX_ADD;
                log.info("新生微信报备请求参数:{}", JsonUtils.toJsonString(params));
                response = HttpUtils.postForm(url, params);
                log.info("新生微信报备返回参数:{}", response);
            } else {
                merchantAccessAuthDO.setType(2);
                CommonResult<Map<String, String>> paramsCommonResult  = HnapayMerchantParamsHandle.alipayApplyParams(channelMerchantBusinessContext, payConfig);
                Map<String, String> params = paramsCommonResult.getData();
                String url = HnapayConstant.DOMAIN_PROD + HnapayConstant.MERCHANT_ALIPAY_ADD;
                log.info("新生支付宝报备请求参数:{}", JsonUtils.toJsonString(params));
                response = HttpUtils.postForm(url, params);
                log.info("新生支付宝报备返回参数:{}", response);
            }
            MerchantAccessInfoDO merchantAccessInfo = channelMerchantBusinessContext.getMerchantAccessDto().getMerchantAccessInfo();
            merchantAccessAuthDO.setAccessId(merchantAccessInfo.getId());
            merchantAccessAuthDO.setSn(merchantAccessInfo.getSn());
            merchantAccessAuthDO.setMchId(splitReq.getChannelNo());

            JSONObject respObj = JsonUtils.parseObj(response);
            if (!"0000".equals(respObj.getStr("resultCode"))) {
                channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
                channelMerchantBusinessContext.setRemark("新生微信/支付宝报备失败：" + respObj.getStr("errorMsg"));
                log.error("新生微信/支付宝报备失败 message: {}", respObj.getStr("errorMsg"));
                merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.REJECT.getCode());
                merchantAccessAuthDO.setRejectReason(respObj.getStr("errorMsg"));
                return;
            } else {
                merchantAccessAuthDO.setSerialCode(respObj.getStr("reportedNo"));
                merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.APPROVEING.getCode());
                channelMerchantBusinessContext.setProcessStatus(Boolean.TRUE);
                channelMerchantBusinessContext.setRemark("报备成功");
            }

            channelMerchantBusinessContext.setMerchantAccessAuthDO(merchantAccessAuthDO);
        } catch (Exception e) {
            log.error("新生微信/支付宝报备请求异常,失败信息 message: {}", e.getMessage(), e);
            channelMerchantBusinessContext.setRemark("新生微信/支付宝报备请求异常,异常信息" + e.getMessage());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
        }
    }

    /**
     * 微信参数配置查询
     *
     * @param channelMerchantAccessAuthQueryContext
     */
    public void processWxConfigQuery(ChannelMerchantAccessAuthQueryContext channelMerchantAccessAuthQueryContext) {
        CommonResult<HnapayConfig> payConfigCommonResult = paramsHandle.channelConfig(channelMerchantAccessAuthQueryContext.getProviderChannelConfig());
        // 配置转换
        if (!payConfigCommonResult.isSuccess()) {
            channelMerchantAccessAuthQueryContext.setRemark(payConfigCommonResult.getMsg());
            channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
            return;
        }
        HnapayConfig payConfig = payConfigCommonResult.getData();
        try {
            List<MerchantAccessAuthDO> merchantAccessAuthList = channelMerchantAccessAuthQueryContext.getMerchantAccessAuthList();
            // 没有微信报备 执行支付宝认证
            if (CollectionUtils.isEmpty(merchantAccessAuthList)) {
                channelMerchantAccessAuthQueryContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.ALIPAY_AUTH);
                return;
            }
            String url = HnapayConstant.DOMAIN_PROD+ HnapayConstant.WECHAT_CONFIG_QUERY;
            MerchantWechatConfigListDto merchantWechatConfigListDto = new MerchantWechatConfigListDto();
            List<MerchantWechatConfigAppIdDto> appIdList = new ArrayList<>();
            List<String> jsApiPath = new ArrayList<>();
            for (MerchantAccessAuthDO merchantAccessAuthDO : merchantAccessAuthList) {
                if (!PayEnums.PAY_TYPE.WECHAT.getCode().equals(merchantAccessAuthDO.getType())) {
                    log.info("新生微信配置查询 非报备非微信类型直接返回 type:{},subMchId:{}", merchantAccessAuthDO.getType(), merchantAccessAuthDO.getSubMchId());
                    continue;
                }
                if (StringUtils.hasText(merchantAccessAuthDO.getMchId())) {
                    log.info("新生微信配置查询 微信子商户号不存在 accessId:{},subMchId:{}", merchantAccessAuthDO.getAccessId(), merchantAccessAuthDO.getSubMchId());
                    continue;
                }
                CommonResult<Map<String, String>> paramsCommonResult = HnapayMerchantParamsHandle.wxConfigQuery(payConfig, merchantAccessAuthDO);
                Map<String, String> params = paramsCommonResult.getData();

                log.info("新生微信配置查询请求参数:{}", JsonUtils.toJsonString(params));
                String response = HttpUtils.postForm(url, params);
                log.info("新生微信配置查询返回参数:{}", response);
                JSONObject respObj = JsonUtils.parseObj(response);
                if (!"0000".equals(respObj.getStr("resultCode"))) {
                    channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
                    channelMerchantAccessAuthQueryContext.setRemark(respObj.getStr("errorMsg"));
                    log.error("新生微信配置查询异常 message: {}", respObj.getStr("errorMsg"));
                }
                try {
                    if (respObj.containsKey("appIdList")) {
                        respObj.getJSONArray("appIdList").stream().forEach(appid -> {
                            MerchantWechatConfigAppIdDto merchantWechatConfigAppIdDto = new MerchantWechatConfigAppIdDto();
                            merchantWechatConfigAppIdDto.setSubAppid(appid.toString());
                            appIdList.add(merchantWechatConfigAppIdDto);
                        });
                    }
                    if (respObj.containsKey("jsapiPathList")) {
                        JSONArray arr =  respObj.getJSONArray("jsapi_path_list");
                        for (int i = 0; i < arr.size(); i++) {
                            jsApiPath.add(arr.get(i).toString());
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    channelMerchantAccessAuthQueryContext.setProcessStatus(false);
                    channelMerchantAccessAuthQueryContext.setRemark(e.getMessage());
                }
            }
            merchantWechatConfigListDto.setAppIdList(appIdList);
            merchantWechatConfigListDto.setJsApiPath(jsApiPath);
            channelMerchantAccessAuthQueryContext.setMerchantWechatConfigListDto(merchantWechatConfigListDto);
        } catch (Exception e) {
            log.error("新生微信配置查询请求失败,失败信息 message: {}", e.getMessage());
            channelMerchantAccessAuthQueryContext.setRemark("新生微信配置查询请求失败,失败信息" + e.getMessage());
            channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
        }
    }

    /**
     * 微信 认证查询，
     *
     * @param channelMerchantAccessAuthQueryContext
     */
    public void processWxAuthQuery(ChannelMerchantAccessAuthQueryContext channelMerchantAccessAuthQueryContext) {
        CommonResult<HnapayConfig> payConfigCommonResult = paramsHandle.channelConfig(channelMerchantAccessAuthQueryContext.getProviderChannelConfig());
        // 配置转换
        if (!payConfigCommonResult.isSuccess()) {
            channelMerchantAccessAuthQueryContext.setRemark(payConfigCommonResult.getMsg());
            channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
            return;
        }

        try {
            HnapayConfig payConfig = payConfigCommonResult.getData();
            List<MerchantAccessAuthDO> merchantAccessAuthList = channelMerchantAccessAuthQueryContext.getMerchantAccessAuthDbList();
            channelMerchantAccessAuthQueryContext.setMerchantAccessAuthList(merchantAccessAuthList);
            channelMerchantAccessAuthQueryContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.ALIPAY_AUTH);

            for (int i = 0; i < merchantAccessAuthList.size(); i++) {
                MerchantAccessAuthDO merchantAccessAuthDO = merchantAccessAuthList.get(i);

                if (!StringUtils.hasText(merchantAccessAuthDO.getSerialCode())) {
                    continue;
                }
                CommonResult<Map<String, String>> authCommonResult = HnapayMerchantParamsHandle.authQuery(payConfig, merchantAccessAuthDO);
                Map<String, String> authParams = authCommonResult.getData();
                String authUrl = HnapayConstant.DOMAIN_PROD+ HnapayConstant.MERCHANT_CONFIRM;
                log.info("新生微信认证查询请求参数:{}", JsonUtils.toJsonString(authParams));
                String authResponse = HttpUtils.postForm(authUrl, authParams);
                log.info("新生微信认证查询返回参数:{}", authResponse);
                JSONObject authResp = JsonUtils.parseObj(authResponse);
                if (!"0000".equals(authResp.getStr("resultCode"))) {
//                    channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
                    channelMerchantAccessAuthQueryContext.setRemark(authResp.getStr("errorMsg"));
                    merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.AUTH_FAIL.getCode());
                    merchantAccessAuthDO.setRejectReason(authResp.getStr("errorMsg"));
                    log.error("新生微信认证查询异常 message: {}", authResp.getStr("errorMsg"));
                    return;
                } else {
                    if ("AUTHORIZE_STATE_AUTHORIZED".equals(authResp.getStr("authorizeState")))
                        merchantAccessAuthDO.setAuthStatus(MerchantEnum.AUTH_STATUS_TYPE.AUTHORIZED.getCode());

                    merchantAccessAuthDO.setRejectReason(authResp.getStr("errorMsg"));
                }
            }
        } catch (Exception e) {
            log.error("新生微信认证查询异常 message: {}", e.getMessage(), e);
            channelMerchantAccessAuthQueryContext.setRemark("新生微信配置查询请求失败,失败信息" + e.getMessage());
//            channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
        }
    }

    /**
     * 微信 appid配置，
     *
     * @param channelMerchantAccessAuthQueryContext
     */
    public void processAliAuthQuery(ChannelMerchantAccessAuthQueryContext channelMerchantAccessAuthQueryContext) {
        CommonResult<HnapayConfig> payConfigCommonResult = paramsHandle.channelConfig(channelMerchantAccessAuthQueryContext.getProviderChannelConfig());
        // 配置转换
        if (!payConfigCommonResult.isSuccess()) {
            channelMerchantAccessAuthQueryContext.setRemark(payConfigCommonResult.getMsg());
            channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
            return;
        }

        try {
            HnapayConfig payConfig = payConfigCommonResult.getData();

            List<MerchantAccessAuthDO> merchantAccessAuthList = channelMerchantAccessAuthQueryContext.getMerchantAccessAuthDbList();
            channelMerchantAccessAuthQueryContext.setMerchantAccessAuthList(merchantAccessAuthList);
            channelMerchantAccessAuthQueryContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.FINISH);
            for (int i = 0; i < merchantAccessAuthList.size(); i++) {
                MerchantAccessAuthDO merchantAccessAuthDO = merchantAccessAuthList.get(i);
                List<Integer> statusList = new ArrayList<>();
                statusList.add(6);
                statusList.add(7);
                statusList.add(9);
                if (statusList.contains(merchantAccessAuthDO.getStatus())) {
                    continue;
                }
                CommonResult<Map<String, String>> authCommonResult = HnapayMerchantParamsHandle.authQuery(payConfig, merchantAccessAuthDO);
                Map<String, String> authParams = authCommonResult.getData();
                String authUrl = HnapayConstant.DOMAIN_PROD+ HnapayConstant.MERCHANT_CONFIRM;;
                log.info("新生支付宝认证查询请求参数:{}", JsonUtils.toJsonString(authParams));
                String authResponse = HttpUtils.postForm(authUrl, authParams);
                log.info("新生支付宝认证查询返回参数:{}", authResponse);
                JSONObject authResp = JsonUtils.parseObj(authResponse);
                if (!"0000".equals(authResp.getStr("resultCode"))) {
                    channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
                    channelMerchantAccessAuthQueryContext.setRemark(authResp.getStr("errorMsg"));
                    merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.AUTH_FAIL.getCode());
                    merchantAccessAuthDO.setRejectReason(authResp.getStr("errorMsg"));
                    log.error("新生支付宝认证查询异常 message: {}", authResp.getStr("errorMsg"));
                    return;
                } else {
                    if ("AUTHORIZE_STATE_AUTHORIZED".equals(authResp.getStr("authorizeState")))
                        merchantAccessAuthDO.setAuthStatus(MerchantEnum.AUTH_STATUS_TYPE.AUTHORIZED.getCode());

                    merchantAccessAuthDO.setRejectReason(authResp.getStr("errorMsg"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("新生支付宝认证查询请求失败,失败信息 message: {}", e.getMessage());
            channelMerchantAccessAuthQueryContext.setRemark("新生支付宝认证查询请求失败,失败信息" + e.getMessage());
            channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
        }
    }
}

